package com.st.bottomnavigation.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.st.bottomnavigation.R;
import com.st.bottomnavigation.ui.activity.GroupActivity;
import com.st.bottomnavigation.ui.adapter.MyFragmentPaperAdapter;
import com.st.bottomnavigation.ui.navbar.AddressBookFragment;
import com.st.bottomnavigation.ui.navbar.DiscoverFragment;
import com.st.bottomnavigation.ui.navbar.HomeFragment;
import com.st.bottomnavigation.ui.navbar.MyFragment;
import com.st.bottomnavigation.ui.zxing.CaptureActivity;
import com.st.bottomnavigation.ui.zxing.DynamicPermissionUtils;
import com.st.bottomnavigation.utils.HttpClientUtils;
import com.st.bottomnavigation.utils.Params;
import com.st.bottomnavigation.utils.PdaDef;
import com.st.bottomnavigation.utils.PermissionChecker;
import com.st.bottomnavigation.utils.StringUtils;
import com.st.bottomnavigation.utils.SystemUtils;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RadioButton rbHome,rbAddressBook,rbDiscover,rbMy;//导航栏按钮组件
    private RadioGroup rgGroup;//导航栏组
    private ViewPager2 viewPager2;//viewPager2组件
    private ActionBar actionBar;
    private TextView titleTextView;
    private RelativeLayout topNavi;
    private TextView title;
    private RelativeLayout rl_title;
    private ImageView more;
    private ImageView scan;
    private IntentIntegrator integrator;
    public static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,       // ***获取设备状态的权限，重要
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            "android.permission.BLUETOOTH_SCAN",
            "android.permission.BLUETOOTH_CONNECT",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.READ_PHONE_STATE",
            "android.permission.USB_PERMISSION"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 申请权限
        PermissionChecker mPermissionChecker = new PermissionChecker(this);
        if (mPermissionChecker.judgePermissions(PERMISSIONS)) {
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 0);
        } else {
            //openBluetooth();
        }
        requestPermissions();
        // TAB
        actionBar = getSupportActionBar();
        actionBar.hide();
        initView();//初始化组件
        initPaper();///初始化pager
        listen();//监听事件
        // 版本升级
        HttpClientUtils.updateAPK(mHandler, Params.CODE_DOWN_PATH, SystemUtils.getVersionName(this));
    }

    /**
     * 初始化组件
     */
    private void initView() {
        title = findViewById(R.id.title);
        rl_title = findViewById(R.id.rl_title);
        more = findViewById(R.id.more);
        scan = findViewById(R.id.scan);
        rbHome = findViewById(R.id.rb_home);//主页
        rbAddressBook = findViewById(R.id.rb_addressBook);//通讯录
        rbDiscover = findViewById(R.id.rb_discover);//发现
        rbMy = findViewById(R.id.rb_my);//我的
        rgGroup = findViewById(R.id.rg_group);//按钮组
        rbHome.setSelected(true);//默认选中第一个
        actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setCustomView(R.layout.custom_action_bar_layout);
        View customView = actionBar.getCustomView();
        titleTextView = customView.findViewById(R.id.text_view_title);
        topNavi = customView.findViewById(R.id.top_navi);
        titleTextView.setText("主页");
        titleTextView.setTextColor(getColor(R.color.black));
//        StatusBarUtil.setColor(MainActivity.this,getResources().getColor(R.color.white),0);
//        StatusBarUtil.setTranslucentForImageView(this, 0, viewById);
    }
    //权限申请
    public void requestPermissions() {
        DynamicPermissionUtils.requestPermissions(this,  DynamicPermissionUtils.PERMISSIONS, 1,
                new DynamicPermissionUtils.OnPermissionListener() {//实现接口方法

                    @Override
                    public void onPermissionGranted() {//获取权限成功
                    }

                    @Override
                    public void onPermissionDenied() {//获取权限失败
                        finish();
                    }
                });
    }
    /**
     * 初始化pager
     */
    private void initPaper() {
        viewPager2 = findViewById(R.id.main_viewpager);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(HomeFragment.getInstance());//主页
        fragments.add(AddressBookFragment.getInstance());//通讯录
        fragments.add(DiscoverFragment.getInstance());//发现
        fragments.add(MyFragment.getInstance());//我的
        MyFragmentPaperAdapter fragmentPaperAdapter = new MyFragmentPaperAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
        viewPager2.setAdapter(fragmentPaperAdapter);
        viewPager2.setUserInputEnabled(false);//禁用滑动
        viewPager2.setOffscreenPageLimit(4);
    }
    /**
     * 初始化监听方法
     */
    private void listen() {
        //导航栏按钮组点击监听事件
        rgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int position) {
                changeTab(position);//改变状态
            }
        });
        //viewPager2滑动监听事件
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
            @Override
            public void onPageSelected(int position) {
                changeTab(position);//改变状态
            }
            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开扫描界面扫描条形码或二维码  CaptureActivity可以使用框架的，也可以复制出来，自定义页面
                Intent openCameraIntent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);



            }
        });

        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupMenu popupMenu=new PopupMenu(getApplication(),more);
                popupMenu.getMenuInflater().inflate(R.menu.popu_menu,popupMenu.getMenu());
                // 设置菜单项点击监听器
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        // 获取点击的菜单项的 ID
                        int itemId = item.getItemId();
                        // 根据菜单项的 ID 进行处理
                        switch (itemId) {
                            case R.id.group:
                                // 处理组件库菜单项点击事件
                                Intent groupIntent = new Intent(MainActivity.this, GroupActivity.class);
                                startActivity(groupIntent);
                                return true;
                            case R.id.addfriend:
                                // 处理添加朋友菜单项点击事件
                                Intent groupIntent2 = new Intent(MainActivity.this, TestActivity.class);
                                startActivity(groupIntent2);
                                return true;
                            case R.id.sao:
                                // 处理扫一扫菜单项点击事件
                                return true;
                            case R.id.help:
                                // 处理帮助与反馈菜单项点击事件
                                return true;
                            default:
                                return false;
                        }
                    }
                });
                popupMenu.show();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 获取扫码结果
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            String contents =result.getContents().trim();
            String barcodeImagePath = result.getBarcodeImagePath();
            Log.d("CaptureActivity2", "barcodeImagePath: " + barcodeImagePath);
        }
        //处理扫描结果（在界面上显示）
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("SCAN_RESULT");
            Toast.makeText(this,"扫描结果："+scanResult,Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DynamicPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HttpClientUtils.MSG_WHAT_LOGIN_SUCCESS: {      // 登录成功
                    JSONObject data = (JSONObject) msg.obj;
                    //登录返回的结果

                    break;
                }
                case HttpClientUtils.MSG_WHAT_UPDATE_APK_SUCCESS: {     // 查询版本成功
                    JSONObject data = (JSONObject) msg.obj;
                    String downloadUrl = data.getString(PdaDef.downloadUrl);
                    if (StringUtils.isNotEmpty(downloadUrl)) {
                        SystemUtils.showAlertDialog(MainActivity.this, "更新", "检测到有新版本,请立即更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                downLoadApk(downloadUrl);
                            }
                        });
                    }
                    break;
                }
            }
        }
    };

    /**
     * 下载APK
     */
    protected void downLoadApk( String downloadUrl) {
        final ProgressDialog pd; // 进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = SystemUtils.getFileFromServer(HttpClientUtils.HOST_URL + downloadUrl, pd);
                    SystemUtils.installApk(MainActivity.this, file);
                    pd.dismiss(); // 结束掉进度条对话框
                } catch (Exception e) {
                    new Handler(getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            SystemUtils.showAlertDialog(MainActivity.this, "下载失败!", null);
                            pd.dismiss();
                            finish();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 切换导航栏状态
     */
    private void changeTab(int position) {
        switch (position) {
            case R.id.rb_home:
            case 0:
                setSelected();
                viewPager2.setCurrentItem(0,false);
                rbHome.setSelected(true);
                titleTextView.setText("主页");
                title.setText("主页");
                rl_title.setVisibility(View.VISIBLE);
                more.setVisibility(View.VISIBLE);
                scan.setVisibility(View.VISIBLE);
                break;
            case R.id.rb_addressBook:
            case 1:
                setSelected();
                viewPager2.setCurrentItem(1,false);
                rbAddressBook.setSelected(true);
                titleTextView.setText("通讯录");
                title.setText("通讯录");
                rl_title.setVisibility(View.VISIBLE);
                more.setVisibility(View.VISIBLE);
                scan.setVisibility(View.GONE);
                break;
            case R.id.rb_discover:
            case 2:
                setSelected();
                viewPager2.setCurrentItem(2,false);
                rbDiscover.setSelected(true);
                titleTextView.setText("发现");
                title.setText("发现");
                rl_title.setVisibility(View.VISIBLE);
                more.setVisibility(View.VISIBLE);
                scan.setVisibility(View.GONE);
                break;
            case R.id.rb_my:
            case 3:
                setSelected();
                viewPager2.setCurrentItem(3,false);
                rbMy.setSelected(true);
                titleTextView.setText("我的");
                rl_title.setVisibility(View.GONE);
                more.setVisibility(View.INVISIBLE);
                scan.setVisibility(View.GONE);
                break;
        }
    }
    /**
     * 所有导航栏设成默认色
     */
    private void setSelected() {
        rbHome.setSelected(false);
        rbAddressBook.setSelected(false);
        rbDiscover.setSelected(false);
        rbMy.setSelected(false);
    }


}